package top.qingyunge.autumn.config;


import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.http.HttpStatus;
import top.qingyunge.autumn.exception.BusinessException;
import top.qingyunge.autumn.vo.Result;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 处理系统内部异常（通用异常）
     */
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) // 指定HTTP状态码
    public Result handleException(Exception e) {
        Result result = Result.error(500, "系统繁忙，请稍后再试");
        log.error("{}:系统异常: {}",result.getTimestamp(), e.getMessage(), e); // 记录日志
        return result; // 返回友好的错误信息
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Result handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        // 获取第一个字段错误信息并返回，也可以拼接所有错误信息
        FieldError fieldError = e.getBindingResult().getFieldError();
        String errorMessage = (fieldError != null) ? fieldError.getDefaultMessage() : "参数错误";
        Result result =Result.error(400, errorMessage);
        log.warn("{}:参数验证失败: {}",result.getTimestamp(), e.getMessage());
        return result;
    }

    @ExceptionHandler(NullPointerException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public Result handleNullPointerException(NullPointerException e) {
        Result result = Result.error(500, "系统发生了空指针异常，请联系管理员");
        log.error("{}:空指针异常: {}", result.getTimestamp(), e.getMessage(), e);
        return result;
    }

    @ExceptionHandler(ArithmeticException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Result handleArithmeticException(ArithmeticException e) {
        Result result = Result.error(400, "计算参数有误");
        log.error("{}:算术异常: {}",result.getTimestamp(), e.getMessage(), e);
        return result;
    }

    @ExceptionHandler(BusinessException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST) // 根据异常含义指定合适的HTTP状态码
    public Result handleBusinessException(BusinessException e) {
        Result result = Result.error(e.getCode(), e.getMessage());
        log.warn("{}:业务异常: {}",result.getTimestamp(), e.getMessage());
        return result;
    }
}